<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use \Illuminate\Support\Facades\Input;

class AreaState extends Model {

	protected $table='area_state';
    protected $_db_select = 'mysql_bgac';

    public $timestamps = false;
    //public $incrementing = false;
    protected $primaryKey = "id";

    //const UPDATED_AT = NULL;
    const CREATED_AT = NULL;    
    public static $DB_FIELDS = ['id', 'area', 'state', 'alias', 'state_label', 'state_style', 'state_mark'];

    public function selectdb($select = ''){
        if ($select) {
            return $this->_db_select = $select;
        }
        return $this->_db_select;
    }
    public function getConnectionName(){
        return $this->selectdb();
    }

    public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);
        \Log::debug(__METHOD__, []);
        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table($this->table)->orderBy("id", "desc")->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $total = $rw->count();
        $data = $rw->get();
        $data = $data->toArray();

        // $data = json_decode($data, true);

        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function SourceCondition($rw) {
        $cond = Input::all();
        
        $rw->where('area', $cond['area'] ?: 0);
        
    }

    public function getCount($area)
    {
        $count = \DB::connection($this->selectdb())->table($this->table)->where("area", $area)->count();
        return $count;
    }

    public function cloneStateDefault($area) {
        $rw = \DB::connection($this->selectdb())->table($this->table)->where('area', 0)->orderBy("id", "desc");
        $count = $rw->count();
        $list = $rw->get();
        \Log::debug('clone area state', [$area, $count]);
        foreach ($list as $obj) {
            $one = new self();
            foreach (self::$DB_FIELDS as $fld) {
                $one->{$fld} = $obj->{$fld};
            }
            
            $one->id = null;
            $one->area = $area;
            $one->save();
        }
    }
}